<template>
  <div class="virtualphone-container">
    <h1>虚拟号码管理</h1>
    <div class="operation-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入号码或地址关键词搜索"
        style="width: 300px;"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" @click="handleAdd">新增号码</el-button>
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 15px;"
    >
      <el-table-column prop="virtualphoneId" label="ID" width="80" />
      <el-table-column prop="virtualphoneNumber" label="虚拟号码" />
      <el-table-column prop="virtualphoneAddress" label="电话地址" />
      <el-table-column prop="pay" label="价格/分钟" />
      <el-table-column prop="supplier" label="服务商" />
      <el-table-column prop="status" label="状态" :formatter="formatStatus" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.virtualphoneId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区 -->
    <div class="pagination-bar" v-if="total > 0">
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        :model="formData"
        ref="formRef"
        label-width="120px"
      >
        <el-form-item label="虚拟号码" prop="virtualphoneNumber" :rules="{ required: true, message: '请输入虚拟号码', trigger: 'blur' }">
          <el-input v-model="formData.virtualphoneNumber" placeholder="请输入虚拟号码" />
        </el-form-item>
        <el-form-item label="电话地址" prop="virtualphoneAddress" :rules="{ required: true, message: '请输入电话地址', trigger: 'blur' }">
          <el-input v-model="formData.virtualphoneAddress" placeholder="请输入电话地址" />
        </el-form-item>
        <el-form-item label="价格/分钟" prop="pay" :rules="{ required: true, message: '请输入价格', trigger: 'blur' }">
          <el-input v-model="formData.pay" type="number" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="服务商" prop="supplier" :rules="{ required: true, message: '请输入服务商', trigger: 'blur' }">
          <el-input v-model="formData.supplier" placeholder="请输入服务商" />
        </el-form-item>
        <el-form-item label="状态" prop="status" :rules="{ required: true, message: '请选择状态', trigger: 'change' }">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { ElMessageBox } from 'element-plus'
import {
  getvirtualphonePageAPI,
  addvirtualphoneAPI,
  updatevirtualphoneAPI,
  deletevirtualphoneAPI,
  searchvirtualphoneAPI
} from '@/apis/virtualphoneAPI'; // 根据实际路径调整

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchKeyword = ref('');

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增虚拟号码');
const formRef = ref(null);
const formData = reactive({
  virtualphoneId: null,
  virtualphoneNumber: '',
  virtualphoneAddress: '',
  pay: 0,
  supplier: '',
  status: 1
});

// 初始化页面加载数据
onMounted(() => {
  fetchVirtualphoneList();
});

// 获取列表数据
const fetchVirtualphoneList = async () => {
  try {
    const response = await getvirtualphonePageAPI(currentPage.value);
    console.log(response);

    if (response.code === 0) {
      tableData.value = response.data.records;
      console.log(tableData.value);
      total.value = response.data.total;
      pageSize.value = response.data.size;
    }
  } catch (error) {
    console.error('获取列表失败:', error);
    ElMessage.error('获取列表失败');
  }
};

// 搜索功能
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    // 关键词为空时加载默认列表
    fetchVirtualphoneList();
    return;
  }

  try {
    const response = await searchvirtualphoneAPI(searchKeyword.value);
    if (response.code === 0) {
      tableData.value = response.data;
      total.value = response.data.length;
    }
  } catch (error) {
    console.error('搜索失败:', error);
    ElMessage.error('搜索失败');
  }
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchVirtualphoneList();
};
// 状态格式化
const formatStatus = (row) => {
  return row.status === 1 ? '启用' : '禁用';
};

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增虚拟号码';
  formData.virtualphoneId = null;
  formData.virtualphoneNumber = '';
  formData.virtualphoneAddress = '';
  formData.pay = 0;
  formData.supplier = '';
  formData.status = 1;
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑虚拟号码';
  // 复制行数据到表单
  formData.virtualphoneId = row.virtualphoneId;
  formData.virtualphoneNumber = row.virtualphoneNumber;
  formData.virtualphoneAddress = row.virtualphoneAddress;
  formData.pay = row.pay;
  formData.supplier = row.supplier;
  formData.status = row.status;
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  const form = formRef.value;
  if (!form) return;

  try {
    await form.validate();

    if (formData.virtualphoneId) {
      // 编辑操作
      const response = await updatevirtualphoneAPI(formData);
      if (response.code === 0) {
        dialogVisible.value = false;
        fetchVirtualphoneList();
        ElMessage.success('修改成功');
      }
    } else {
      // 新增操作
      const response = await addvirtualphoneAPI(formData);
      if (response.code === 0) {
        dialogVisible.value = false;
        fetchVirtualphoneList();
        ElMessage.success('新增成功');
      }
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
    return false;
  }
};

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条数据吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const response = await deletevirtualphoneAPI(id);
    if (response.code === 0) {
      ElMessage.success('删除成功');
      fetchVirtualphoneList();
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 引入Element组件
const { proxy } = getCurrentInstance();
const ElMessage = proxy.$message;
</script>

<style lang="scss" scoped>
.virtualphone-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
}

.operation-bar {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.pagination-bar {
  margin-top: 15px;
  text-align: right;
}
</style>
